import java.sql.ResultSet;
import java.sql.SQLException;


public class EndGame {
	public static void writeResultsToDB(String pl1, String pl2, String winner) throws SQLException{
		//Write history to DB
		String query="INSERT INTO history (player1, player2, winner) VALUES ('"+pl1+"','"+pl2+"','"+winner+"');";
		PostgresDB.sendQuery(query);

		if(winner.equals(pl1)){
			updateWinsAndLoses(pl1, pl2);

		}
		else{
			updateWinsAndLoses(pl2, pl1);

		}
	}

	public static void updateWinsAndLoses(String pl1, String pl2)
			throws SQLException {
		//Increasing wins for winner
		String query;
		query="SELECT wins, loses FROM users WHERE username ='"+pl1+"';";
		ResultSet result = PostgresDB.sendQuery(query);

		int wins=0;
		int loses=0;
		while (result.next()) { // process results one row at a time
			wins=result.getInt(1);
			loses=result.getInt(2);
		}
		float ratio;
		wins++;
		
		if(loses==0){
			ratio=wins;
		}
		else{
			ratio= (wins/(float)loses);
		}
		
		query="UPDATE users SET wins="+wins+",ratio="+ratio+" WHERE username ='"+pl1+"';";
		PostgresDB.sendQuery(query);


		//Increasing loses for looser
		query="SELECT wins, loses FROM users WHERE username ='"+pl2+"';";
		result = PostgresDB.sendQuery(query);
		while (result.next()) { // process results one row at a time
			wins=result.getInt(1);
			loses=result.getInt(2);
		}
		ratio=0;		
		loses++;
		ratio= (wins/(float)loses);
		query="UPDATE users SET loses="+loses+",ratio="+ratio+" WHERE username ='"+pl2+"';";
		PostgresDB.sendQuery(query);
	}
}
